package com.hotel.payment.controller;

import com.hotel.common.utils.DBTools;
import com.hotel.common.utils.Result;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping({"/payment/payments", "/api/payment/payments"})
public class PaymentController {

    @GetMapping
    public Result<List<Map<String, String>>> list(@RequestParam(name = "orderId", required = false) Long orderId) {
        String base = "SELECT id, order_id AS orderId, pay_channel AS payChannel, pay_status AS payStatus, amount, created_at AS createdAt FROM payment";
        List<Map<String, String>> data = orderId == null
                ? DBTools.query(base + " ORDER BY id DESC")
                : DBTools.query(base + " WHERE order_id=? ORDER BY id DESC", orderId);
        return Result.success(data);
    }

    @PostMapping
    public Result<Map<String, Object>> pay(@RequestBody Map<String, Object> body) {
        try {
            Long orderId = Long.parseLong(body.get("orderId").toString());
            String paymentMethod = (String) body.getOrDefault("paymentMethod", "alipay");
            Double amount = Double.parseDouble(body.get("amount").toString());
            
            // 转换支付方式
            String payChannel = "ALIPAY";
            if ("wechat".equalsIgnoreCase(paymentMethod)) {
                payChannel = "WECHAT";
            }
            
            // 插入支付记录
            String paymentSql = "INSERT INTO payment(order_id,pay_channel,pay_status,amount) VALUES(?,?,?,?)";
            DBTools.update(paymentSql, orderId, payChannel, "SUCCESS", amount);
            String paymentId = DBTools.querySingle("SELECT LAST_INSERT_ID() AS id");
            
            // 更新订单状态为已支付
            String orderSql = "UPDATE orders SET status='PAID' WHERE id=?";
            DBTools.update(orderSql, orderId);
            
            // 返回支付结果
            Map<String, Object> result = new java.util.HashMap<>();
            result.put("paymentId", Long.valueOf(paymentId));
            result.put("orderId", orderId);
            result.put("status", "SUCCESS");
            result.put("message", "支付成功");
            result.put("paymentUrl", "https://example.com/payment/success?orderId=" + orderId);
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.fail("支付失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public Result<Void> refund(@PathVariable("id") Long id) {
        String sql = "UPDATE payment SET pay_status='REFUNDED' WHERE id=?";
        DBTools.update(sql, id);
        return Result.success();
    }

    @GetMapping("/health")
    public Result<String> health() {
        return Result.success("Payment service is running on port 8083");
    }
}
